/**
 * 
 */
package com.mc.huaweicloud;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.core.http.HttpConfig;
import com.huaweicloud.sdk.ocr.v1.OcrClient;
import com.huaweicloud.sdk.ocr.v1.model.GeneralTableRequestBody;
import com.huaweicloud.sdk.ocr.v1.model.RecognizeGeneralTableRequest;
import com.huaweicloud.sdk.ocr.v1.model.RecognizeGeneralTableResponse;
import com.huaweicloud.sdk.ocr.v1.region.OcrRegion;
import com.mc.file.Base64Util;

import cn.hutool.core.lang.Console;

/**
 * @author w.weizhen
 * 识别解析 表格图片, 生成表格文件
 */
public class GeneralTable {
    private static final String ak = "FNV2AAKWAJE7XJQCURKQ";
    private static final String sk = "8AD5Jz7jBZD0Uxbrq3wmEz7SK1E5aZJ6oa8f3R3O";
    
    private static final String original_path = "D:/文件/临时文件/表格图片/original/";//表格图片目录
    private static final String generate_path = "D:/文件/临时文件/表格图片/generate/";//生成表格目录
    
    /**
     * @param args
     */
    public static void main(String[] args) {
        //获取指定目录下的所有文件
        List<String> names = new ArrayList<String>();
        File file = new File(original_path);
        if (file.exists()) 
        {
            File[] files = file.listFiles();
            for (File file2 : files) {
                String name = file2.getName();
                //name = name.substring(0,name.lastIndexOf("."));
                if (file2.isFile()&&StringUtils.isNotBlank(name)&&!names.contains(name)) {
                    names.add(name);
                }
            }
        }
        
        if (CollectionUtils.isEmpty(names)) {System.err.println("names is null!");return;}
        for (int i = 0; i < names.size(); i++) 
        {
            analysis(names.get(i));
            //break;
        }
    }
    
    //将图片解析成为json内容
    private static void analysis(String name)
    {
        // 使用默认配置
        HttpConfig config = HttpConfig.getDefaultHttpConfig();
        // 初始化客户端认证信息，使用当前客户端初始化方式可不填 projectId/domainId
        ICredential auth = new BasicCredentials().withAk(ak).withSk(sk);
        // 初始化指定云服务的客户端 {Service}Client ，以初始化OCR服务的 OcrClient 为例
        OcrClient client = OcrClient.newBuilder().withHttpConfig(config).withCredential(auth).withRegion(OcrRegion.valueOf("cn-north-4")).build();
        
        // 以调用通用表格识别接口 RecognizeGeneralTable 为例
        RecognizeGeneralTableRequest request = new RecognizeGeneralTableRequest();
        GeneralTableRequestBody body = new GeneralTableRequestBody();
        //body.withUrl("图片的url");
        body.withImage(Base64Util.encryptToBase64(original_path + name));
        request.withBody(body);
        try {
            RecognizeGeneralTableResponse response = client.recognizeGeneralTable(request);
            System.out.println(JSONObject.toJSONString(response));
            if (200 == response.getHttpStatusCode()) {
                //JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(response));
                JSONArray datas = JSONArray.parseArray(JSONObject.toJSONString(response.getResult().getWordsRegionList()));
                //将解析内容生成表格文件
                generate(name, datas);
            }else {
                System.err.println(JSONObject.toJSONString(response));
            }
        } catch (ConnectionException e) {
            e.printStackTrace();
        } catch (RequestTimeoutException e) {
            e.printStackTrace();
        } catch (ServiceResponseException e) {
            e.printStackTrace();
            System.err.println(e.getHttpStatusCode());
            System.err.println(e.getErrorCode());
            System.err.println(e.getErrorMsg());
        }
    }
    
    //将json内容生成为ex文件
    private static void generate(String name, JSONArray datas)
    {
        //List<List<String>> heads = new ArrayList<List<String>>(20);
        //heads.add(new ArrayList<String>(20));
        //List<List<Object>> words = new ArrayList<List<Object>>(20);
        //words.add(new ArrayList<Object>(20));
        
        name = name.substring(0, name.lastIndexOf("."));//去除名称的后缀
        //标题和内容
        List<List<String>> heads = new ArrayList<List<String>>();
        List<List<String>> words = new ArrayList<List<String>>();
        //生成一个空的表格
        int length = 20;
        for (int i = 0; i < length; i++) 
        {
            List<String> head = new ArrayList<String>();head.add("");
            List<String> word = new ArrayList<String>();
            for (int j = 0; j < length; j++) 
            {
                word.add("");
            }
            heads.add(head);
            words.add(word);
        }
        //填充内容
        //Console.log(heads);
        //Console.log(words);
        for (int i = 0; i < datas.size(); i++) 
        {
            JSONObject data=datas.getJSONObject(i);
            //是不是空的内容
            if(data==null || data.getInteger("wordsBlockCount") < 2){continue;}
            
            //Console.log("data");
            //Console.log(data.toJSONString());
            JSONArray wordsBlocks = data.getJSONArray("wordsBlockList");
            //Console.log("wordsBlocks");
            //Console.log(wordsBlocks.toJSONString());
            for (int j = 0; j < wordsBlocks.size(); j++) 
            {
                JSONObject wordsBlock=wordsBlocks.getJSONObject(j);
                //Console.log("wordsBlock");
                //Console.log(wordsBlock.toJSONString());
//                //标题作为文件名一部分
//                if ("text".equals(data.get("type"))) 
//                {
//                    name += wordsBlock.getString("words");
//                }
                
                if ("table".equals(data.get("type"))) 
                {
                    List<Integer> columns = wordsBlock.getJSONArray("columns").toJavaList(Integer.class);
                    List<Integer> rows = wordsBlock.getJSONArray("rows").toJavaList(Integer.class);
                    String word = wordsBlock.getString("words");
                    word = word.replaceAll("\\r?\\n", "");//去除换行符
                    for (int k = 0; k < columns.size(); k++) 
                    {
                        for (int k2 = 0; k2 < rows.size(); k2++) 
                        {
                            //words.get(rows.get(k2)).add(columns.get(k), word);
                            Integer row = rows.get(k2);
                            Integer column = columns.get(k);
                            
                            if (row < 1) {heads.get(column).set(row, word);}
                            if (row > 0) {words.get(row-1).set(column, word);}
                        }
                    }
                }
            }
        }
        
        //生成表格文件
        //Console.log();
        Console.log(heads);
        Console.log(words);
        EasyExcel.write(generate_path + name + ".xlsx").head(heads).sheet("Sheet").doWrite(words);
        
        //生成json文件
//        JSONObject data = new JSONObject();
//        data.put("datas", datas);
//        data.put("heads", heads);
//        data.put("words", words);
//        try {
//            FileUtils.writeStringToFile(new File(generate_path + name + ".json"), data.toString(), "UTF-8");
//        } catch (Exception e) {
//            // TODO: handle exception
//        }
    }
}